<?php

class ORM_Finder{
    
    static function find($model, $conditions = null, $fields = '*', $order = null, $limit = null, $debug=FALSE,$memtime=0) {
        
        if (!empty($conditions)) {
            $where = "WHERE";
            if (is_array($conditions)) {
                foreach ($conditions as $field => $value) {
                    $where .= " `$field` = ?";
                    $values[] = $value;
                }
            } else {
                $where .= ' '.$conditions;
                $values = array();
            }
        } else {
            $where = '';
            $values = array();
        }
        
        is_array($fields) ? $fields = join(',', $fields) : $fields;
        
        if (!empty($order)) {
            $order = 'ORDER BY '.$order;
        }
        if (!empty($limit)) {
            $limit = 'LIMIT '.$limit;
        }
        
        $table 		= call_user_func(array($model, 'getTableName'), $conditions);
        $sql		= "SELECT $fields FROM {#prefix#}".$table." $where $order $limit";
        $memkey	= md5($sql);

        $return = self::getData($memkey, $memtime);
                
        #调试状态
        if($debug){
        	echo $sql."<br/>";
        }
        if(empty($return)){
        	//exit('sss');
            $conn = ConnectionManager::getConn(call_user_func(array($model, 'getConn')));
	        $rs = $conn->query($sql, $values);
	        $return = array();
	        while ($data = $rs->fetch()) {
	            $m = new $model;
	            foreach ($data as $key => $d) {
	                call_user_func(array($m, 'set'.$key), $d);
	            }
	            $m->setNew(false);
	            $return[] = $m;
	        }
	        #存储数据
	        self::setData($memkey, $memtime,$return);
        }
        return $return;
    }
    
    /**
     * 检索一条数据
     *
     * @param string $model
     * @param array $conditions
     * @param array $fields
     * @param string $order
     * @return unknown
     */
    static function findOne($model, $conditions = null, $fields = '*', $order = null, $debug=NULL,$memtime=0) {
        $r = self::find($model, $conditions, $fields, $order, 1,$debug, $memtime);
        return isset($r[0])?$r[0]:null;
    }
    
    static function findById($model, $id,$debug=FALSE,$memtime=1800) {
        $r = self::find($model, array('id' => $id), '*', null, 1,$debug, $memtime);
        return $r[0];
    }
    
    /**
     * 返回统计
     * @param String $model
     * @package Array $conditions
     * 
     */
    static function findCount($model, $conditions = null,$filed='id',$memtime=0) {
        
        if (!empty($conditions)) {
            $where = "WHERE";
            if (is_array($conditions)) {
                foreach ($conditions as $field => $value) {
                    $where .= " $field = ?";
                    $values[] = $value;
                }
            } else {
                $where .= ' '.$conditions;
                $values = array();
            }
        } else {
            $where = '';
            $values = array();
        }
                
        $table	= call_user_func(array($model, 'getTableName'), $conditions);
        $sql	= "SELECT count($filed) FROM {#prefix#}".$table." $where";
        $memkey	= md5($sql);
        $return	= self::getData($memkey, $memtime);
		//echo $sql;
        if(empty($return))
        {
	       	$conn = ConnectionManager::getConn(call_user_func(array($model, 'getConn')));
	        $rs = $conn->query($sql);
	        $return = $rs->fetchColumn();
	        self::setData($memkey, $memtime, $return);
        }
        return $return;
    }
    
    /**
     * 根据sql语句查询
     * @param 	String $sql
     * @param 	String $model
     */
    static function sqlAll($sql, $model='Admin',$memtime=0)
    {
    	$sql = str_replace('pre_', '{#prefix#}', $sql);
       	$key	= md5($key);
    	$return	= self::getData($key, $memtime);
    	
    	//echo $sql;
    	if(empty($return))
    	{
	    	$conn = ConnectionManager::getConn(call_user_func(array($model, 'getConn')));
	    	$rs = $conn->query($sql);
	        $return = array();
	        while ($data = $rs->fetch()) {
	            $m = new $model;
	            foreach ($data as $key => $d) {
	                call_user_func(array($m, 'set'.$key), $d);
	            }
	            $m->setNew(false);
	            $return[] = $m;
	        }

	        self::setData($key, $memtime,$return);
    	}
        
        return $return;
    }
    
    /**
     * 根据sql语句查询
     */
    static function sqlCount($sql, $model='Admin', $memtime=0)
    {
    	$sql 	= str_replace('pre_', '{#prefix#}', $sql);
		$memkey	= md5($sql);
		$return	= self::getData($memkey, $memtime);
		#查询数据
		if(empty($return))
		{   	
	    	$conn = ConnectionManager::getConn(call_user_func(array($model, 'getConn')));
	    	$rs = $conn->query($sql);
	        $return = $rs->fetchColumn();
	        self::setData($memkey, $memtime, $return);
		}

        return $return;
    }
    
    static function getCacheDir($name)
    {
    	$dir	= ROOT.'/data/'.substr($name,0,6).'/'.substr($name,6,6).'/'.substr($name,12,6).'/'.substr($name,18,6).'/';
    	if(!is_dir($dir))
    	{
    		mkdir($dir, 0777, TRUE);
    	}
    	return $dir.substr($name,24,12);
    }
    
    /**
     * 通过文件获取缓存数据
     *
     * @param md5($sql) $name
     * @param Int $time
     * @return Data
     */
    static function getFileData($name, $time=0)
    {
    	$file	= self::getCacheDir($name);
    	if(!file_exists($file)){
    		$data	= '';
    	}elseif((time()-filemtime($file))>$time){
    		$data	= '';
    	}else{
    		$data	= file_get_contents($file);
    		$data	= unserialize($data);
    	}
    	return $data;
    }
    
    /**
     * 设置缓存数据到文件
     *
     * @param md5($sql) $name
     * @param Data $data
     */
    static function setFileData($name, $data)
    {
    	$file	= self::getCacheDir($name);
    	file_put_contents($file, $data);
    }
    
  	private static function setData($key, $memtime, $data)
  	{
  		if($memtime>0){
	  		#存储数据
	        if(MY_MEMCACHE==1){
	        	$mem->set($key, $return, 0, $memtime);
	        }elseif (MY_FILE_CACHE==1){
	        	$file	= self::getCacheDir($key);
	        	$data	= serialize($data);
	        	self::setFileData($key, $data);
	        }
  		}
  	}
  	
  	private static function getData($memkey, $memtime)
  	{
  		$return = '';
  		if($memtime>0){
	  		if(MY_MEMCACHE==1){
		        $mem	= ORM_Memcache::getInstance();
		        $return	= $mem->get($memkey);
	        }elseif(MY_FILE_CACHE==1){
				$return	= self::getFileData($memkey, $memtime);
			}
  		}
		return $return;
  	}
}
